﻿using Flurl.Http;
using Newtonsoft.Json.Linq;
using Pay.Core;
using Pay.DTO;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Pay.IService;
using Autofac;

namespace Pay.Token.Utils {
    /// <summary>
    /// 云平台接口方法
    /// </summary>
    public class HChannelApi {
        private static object syncRoot = new object();
        private static HChannelApi instance;
        public static HChannelApi Current {
            get {
                if (instance == null) {
                    lock (syncRoot) {
                        if (instance == null)
                            instance = new HChannelApi();
                    }
                }
                return instance;
            }
        }

        /// <summary>
        /// 调用商付宝接口
        /// </summary>
        /// <returns>The API.</returns>
        /// <param name="data">Data.</param>
        public async Task<T> PostApi<T>(head_req data) where T : result_base, new() {
            var log = IocHelper.Get<ILogHelper>("info");
            var app_sortJson = sign(data.ToJson());
            try {
                var app_sign = RSAFromPkcs.sign(app_sortJson, t_RequestMethod.PrivateKey, "utf-8");
                data.sign = app_sign;
                var result = await t_RequestMethod.api_url.PostJsonAsync(data).ReceiveJson<T>();
                if (result.result_code != 1000) {
                    log.Error(t_RequestMethod.api_url + "(" + data.method + "):" + result.result_msg);
                    log.Error(app_sortJson);
                }
                return result;
            } catch (FlurlHttpException ex) {
                log.Error(t_RequestMethod.api_url + "(" + data.method + "):" + ex.Message);
                log.Error(app_sortJson);
                return new T { result_code = 0, result_msg = "请求失败" };
            }
        }

        

        /// <summary>
        /// 直接转字典
        /// </summary>
        /// <returns>The to key query2.</returns>
        /// <param name="json">Json.</param>
        public string sign(string json) {
            var collection = json.ToObject<SortedDictionary<string, object>>();
            string result = string.Empty;
            foreach (var kv in collection) {
                if (kv.Key == "sign") continue;
                if (kv.Value is JArray) {
                    string str = "";
                    var arrs = kv.Value as JArray;
                    foreach (var obj in arrs) {
                        if (obj.Type.ToString().Equals("String")) continue;
                        str += FillStringBuilder(obj.ToObject<SortedDictionary<string, object>>());
                    }
                    //str = str.Trim('&');
                    //result += "&" + kv.Key + "=" + str;
                    result += str;
                } else if (kv.Value is JObject) {
                    //result += "&" + kv.Key + "=" + FillStringBuilder((kv.Value as JObject).ToObject<SortedDictionary<string, object>>());
                    result += FillStringBuilder((kv.Value as JObject).ToObject<SortedDictionary<string, object>>());
                } else {
                    if (kv.Value != null && !string.IsNullOrEmpty(kv.Value.ToString()))
                        result += "&" + kv.Key + "=" + kv.Value;
                }
            }
            result = result.Trim('&');
            return result;
        }

        private string FillStringBuilder(SortedDictionary<string, object> dic) {
            string result = string.Empty;
            foreach (var kv in dic) {
                if (kv.Value is JObject)
                    //result += "&" + kv.Key + "=" + FillStringBuilder((kv.Value as JObject).ToObject<SortedDictionary<string, object>>());
                    result += FillStringBuilder((kv.Value as JObject).ToObject<SortedDictionary<string, object>>());
                else if (kv.Value is JArray) {
                    string str = "";
                    var arrs = kv.Value as JArray;
                    foreach (var obj in arrs) {
                        if (obj.Type.ToString().Equals("String"))
                            continue;
                        str += FillStringBuilder(obj.ToObject<SortedDictionary<string, object>>());
                    }
                        
                    //result += "&" + kv.Key + "=" + str;
                    result += str;
                } else {
                    if (kv.Value != null && !string.IsNullOrEmpty(kv.Value.ToString()))
                        result += "&" + kv.Key + "=" + kv.Value;
                }
            }
            return result;
        }
    }
    /// <summary>
    /// 分销收益操作类
    /// </summary>
    public class DistributionHelper {
        private static decimal user = 0.1M;
        private static decimal token = 0.5M;
        /// <summary>
        /// 计算分销收益金额
        /// </summary>
        /// <param name="price"></param>
        /// <param name="user_type"></param>
        /// <returns></returns>
        public static decimal GetProfitByLevel(decimal price,UserType user_type) {
            return (user_type == UserType.user ? price * user : price * token).NumberToFixedNoRound(2);
        }
    }
}
